package com.example.mychat.Controller;

import com.example.mychat.entity.Authorities;
import com.example.mychat.entity.Users;
import com.example.mychat.mapper.AuthoritiesMapper;
import com.example.mychat.mapper.UsersMapper;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.security.Principal;

@Tag(name = "OAuth2.0控制")
@RestController
public class OAuthController {
    @Resource
    UsersMapper usersMapper;

    @Resource
    AuthoritiesMapper authoritiesMapper;

    @GetMapping("/")
    public String hello(Principal principal,
                        @RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient,
                        @AuthenticationPrincipal OAuth2User oauth2User,
                        HttpSession session) {
        System.out.println(principal.toString());
        System.out.println(authorizedClient.getClientRegistration().getClientName());
        System.out.println(oauth2User.getAttributes().toString());
        String username = principal.getName();
        String Flag = String.valueOf(session.getAttribute("username"));
        if (!Flag.equals("null")) {
            session.removeAttribute("username");
        }
        session.setAttribute("username", username);
        Users users = usersMapper.selectById(username);
        if (users == null) {
            users = new Users(username, "gitee");
            usersMapper.insert(users);
            Authorities authorities = new Authorities(username, "USER");
            authoritiesMapper.insert(authorities);
        }
        return "hello " + username;
    }
}
